<?php

// ACP Header - START
if (!empty($setmodules))
{
	$module['Users']['Warnings'] = basename(__FILE__) . '?mode=list';
	return;
}
$mode = isset($_GET['mode']) ? $_GET['mode'] : '';
$warn_id = isset($_GET['id']) ? (int) $_GET['id'] : '';
$submit  = isset($_POST['submit']);
$show  = isset($_POST['Show']);
require('./pagestart.php');
// ACP Header - END

require(LANG_DIR .'lang_admin_warning.php');
$_main = BB_ROOT . 'images/warn/';
$images['user_warned_rank'] = $_main .'user_warned_rank.gif';
$images['user_banned_rank'] = $_main .'user_banned_rank.gif';
$images['user_nulled_warn'] = $_main .'user_nulled_warn.gif';

$select_list = '<select name = CHOICE>
<option value = "1" selected>' . $lang['ALL'] . '</option>
<option value = "2">' . $lang['ACTING'] . '</option>
<option value = "3">' . $lang['STATISTICS'] . '</option>
</select>';
	
if ($mode != 'edit')
{
if (empty($choice_id)) 
{
	$choice_id = 1;
}

if ($show) 
{
	$choice_id = intval($_POST['CHOICE']);
}
	if ($choice_id == 1)
	{
		$sql = "SELECT w.*, t.*, u.user_id, u.username, u.user_warnings, u.user_banned, u2.username AS poster FROM ". BB_WARNINGS ." w, ". BB_USERS ." u, ". BB_WARNINGS_TEXT ." t, ". BB_USERS ." u2
		WHERE u.user_id = w.warning_user_id AND t.warning_id = w.warning_id AND u2.user_id = w.warning_poster_id ORDER BY w.warning_user_id";
		$mode = 'list';
	//Выдаёт список пользователей, у которых есть действующие предупреждения, но с  проверкой действия по полю warning_proceed таблицы BB_WARNINGS
//	$sql = "SELECT w.*, t.*, u.user_id, u.username, u.user_warnings, u.user_banned, u2.username AS poster FROM ". BB_WARNINGS ." w, ". BB_USERS ." u, ". BB_WARNINGS_TEXT ." t, ". BB_USERS ." u2
//	WHERE w.warning_proceed = 0 AND u.user_id = w.warning_user_id AND t.warning_id = w.warning_id AND u2.user_id = w.warning_poster_id ORDER BY w.warning_user_id";
	} else if ($choice_id == 2)
	{
		$sql = "SELECT u.user_id, u.username, u.user_warnings, u.user_banned, w.warning_id, w.warning_type,
     	    w.warning_post_id, t.warning_text, u2.username AS poster,
		    w.warning_posted, w.warning_expires, w.warning_proceed
		    FROM ". BB_USERS ." u
		    LEFT JOIN ". BB_WARNINGS      ." w ON (w.warning_user_id = u.user_id)
		    LEFT JOIN ". BB_WARNINGS_TEXT      ." t ON (t.warning_id = w.warning_id)
		    LEFT JOIN ". BB_USERS      ." u2 ON (u2.user_id = w.warning_poster_id)
		    WHERE u.user_warnings != 0 OR u.user_banned != 0 ORDER BY u.user_id";
		$mode = 'list';
	} else
	{
		$mode = 'stat';	
	}
}
	
if ($mode == 'list')
{
	if (!$result = DB()->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain warning data", "", __LINE__, __FILE__, $sql);
	}
	$result = DB() -> sql_query($sql) or die(mysql_error());
	$warn_count = DB()->num_rows($result);
	$row = DB()->sql_fetchrowset($result);
	if ($choice_id == 1)
	{
		$lang_title_text = 'WARNING_LIST_TITLE';
		$lang_text = 'WARNING_ALL_LIST_TEXT_DESC';	
	} 
	if ($choice_id == 2)
	{
		$lang_title_text = 'WARNING_LIST_ACTING_TITLE';
		$lang_text = 'WARNING_LIST_ACTING_TEXT_DESC';	
	} 
	$template->assign_vars(array(
		'TPL_WARNINGS_LIST' => true,
		"L_ACTING_WARNING_LIST_TITLE" => $lang[$lang_title_text],
		"L_WARNING_LIST_TEXT" => $lang[$lang_text],
		'S_LIST_SELECT' => $select_list,
		"S_WARNING_ACTION" => append_sid("admin_warning.php")
		));

	for($i = 0; $i < $warn_count; $i++)
	{
		$user_id = $row[$i]['user_id'];
		$row_class = !($i % 2) ? 'row1' : 'row2';
//-----------------------------------------------------------------------------------------------------------------------------------------		

		if ( ( $row[$i]['user_warnings'] >= $bb_cfg['warnings_per_ban'] ) || $row[$i]['user_banned'] )
		{
			$poster_rank = $lang['BANNED_RANK'];
			$rank_image =  '<img src="' . $images['user_banned_rank'] . '" alt="' . $poster_rank . '" title="' . $poster_rank . '" border="0" />';
		}
		elseif ( $row[$i]['user_warnings'] )
		{
			$poster_rank = sprintf($lang['WARNED_RANK'], $row[$i]['user_warnings']);
			$rank_image =  '<img src="' . $images['user_warned_rank'] . '" alt="' . $poster_rank . '" title="' . $poster_rank . '" border="0" />&nbsp;<br />';
			$rank_image = str_repeat($rank_image, $row[$i]['user_warnings']);
		}

		if (($row[$i]['warning_type']) == '')
		{
			$warning_icon = $images['user_nulled_warn'];
		}
		 else switch ( $row[$i]['warning_type'] )
		{
			case WARNING_TYPE_WARNING:
				$warning_icon = $images['user_warned_rank'];
			break;
					
			case WARNING_TYPE_BAN:
				$warning_icon = $images['user_banned_rank'];
			break;
		};
		$warning_icon = '<img src="' . $warning_icon . '" border="0" alt="">';

//-----------------------------------------------------------------------------------------------------------------------------------------
		$edit_mode = "<a class='gensmall' href='admin_warning.php?mode=edit&id=$user_id'>" . $lang['EDIT_WARNING'] . "</a>";
		
		$posted_date = $row[$i]['warning_posted'];
		if ($posted_date == '')
		{
			$posted_date = '-';
		} 
		else $posted_date = date('d-m-Y H:i',$row[$i]['warning_posted']);
		
		$expires_date = $row[$i]['warning_expires'];

		if ($expires_date == -1)
		{
			$expires_date = $lang['WT_INFINITY'];
		} else if ($expires_date == '')
		{
			$expires_date = '-';
		}
		else $expires_date = date('d-m-Y H:i',$row[$i]['warning_expires']);
		
		$warning_actions = array();
		$warning_actions[] = '<a class="gensmall" href="../warnings.php?mode=edit_warning&amp;' . POST_WARNING_URL . '=' . $row[$i]['warning_id'] . '&amp;sid=' . $userdata['session_id'] . '" target="_blank">' . $lang['EDIT_WARNING'] . '</a>';

		if ( !$row[$i]['warning_proceed'] )
		{
			$warning_actions[] = '<a class="gensmall" href="../warnings.php?mode=remove_warning&amp;' . POST_WARNING_URL . '=' . $row[$i]['warning_id'] . '&amp;sid=' . $userdata['session_id'] . '" target="_blank">' . $lang['REMOVE_WARNING'] . '</a>';
		}
		$warning_actions[] = '<a class="gensmall" href="../warnings.php?mode=delete_warning&amp;' . POST_WARNING_URL . '=' . $row[$i]['warning_id'] . '&amp;sid=' . $userdata['session_id'] . '" target="_blank">' . $lang['DELETE_WARNING'] . '</a>';
		
		if 	($expires_date == '-')
		{
			$warn_action = $edit_mode;
		} else
		{
			$warn_action = implode($warning_actions, '<br />');
		}
		$template->assign_block_vars("UsWarn", array(
			"ROW_CLASS" => $row_class,
			"USER_ID" => $row[$i]['user_id'],
			"USER" => $row[$i]['username'],
			"USER_WARNINGS" => $row[$i]['user_warnings'] + $row[$i]['user_banned'],
			"WARNING_TYPE" => $row[$i]['warning_type'],
			'WARNING_ICON' => $warning_icon,			
			"WARNING_TEXT" => $row[$i]['warning_text'],
			"POSTER_NAME" => $row[$i]['poster'],
			"WARN_POSTED_DATE" => $posted_date,
			"WARN_EXPIRES_DATE" => $expires_date,
			'WARNING_ACTIONS' => $warn_action
			)) ;
	}
//______________________________________________________________________________________________________________________________________
}

if ($mode == 'edit' && $warn_id)
{
	$sql = "SELECT *
		FROM ". BB_USERS ." 
		WHERE user_id = " . $warn_id;
	if(!$result = DB()->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain warning data", "", __LINE__, __FILE__, $sql);
	}
	$result = DB() -> sql_query($sql) or die(mysql_error());
	$template->assign_vars(array(
		'TPL_WARNINGS_EDIT' => true,		
		"S_WARNING_ACTION" => append_sid("admin_warning.php")
		));
	while($row = DB() -> sql_fetchrow($result)) 
	{
		$user_id = $row['user_id'];
		$user_id_warn = $row['user_id'];
		$username = $row['username'];		
		$user_warnings = $row['user_warnings'];
		$user_banned = $row['user_banned'];
		
		$template->assign_block_vars("UsWarnEdit", array(
			"USER_ID" => $user_id,
			"USER" => $username,			
			"USER_WARNINGS" => $user_warnings,
			"USER_BANNED" => $user_banned
		)) ;
	}		
}
if ($submit) 
{
	$warn_id = $_POST['USER_ID'];
	$user_warnings = ( !empty($_POST['USER_WARNINGS']) ) ? trim(strip_tags( $_POST['USER_WARNINGS'] ) ) : '';
	$user_warnings = intval(stripslashes($user_warnings));
	$user_banned = ( !empty($_POST['USER_BANNED']) ) ? trim(strip_tags( $_POST['USER_BANNED'] ) ) : '';		
	$user_banned = intval(stripslashes($user_banned));
	$sql = "UPDATE " . BB_USERS . " SET
	user_warnings = '" . $user_warnings . "',
	user_banned = '" .  $user_banned . "'
	where user_id = '" . $warn_id . "'";
	if( !DB()->sql_query($sql) )
	{
		message_die(GENERAL_ERROR, "Failed to update general configuration for $username", "", __LINE__, __FILE__, $sql);
	}
	$message = $lang['WARNING_USERS_UPDATED'] . "<br /><br />" . sprintf($lang['CLICK_RETURN_WARNING_MANAGEMENT'], "<a href=\"" . append_sid("admin_warning.php?mode=list") . "\">", "</a>") . "<br /><br />" . sprintf($lang['CLICK_RETURN_ADMIN_INDEX'], "<a href=\"" . append_sid("index.php?pane=right") . "\">", "</a>");
	message_die(GENERAL_MESSAGE, $message);
}
if ($mode == 'stat')
{
	$total_warn = 0;
	$total_ban = 0;
//	Осуществляем выборку по количеству когда-либо предупреждённых юзеров
	$sql = "SELECT DISTINCT w.warning_user_id, u.user_id, u.username FROM ". BB_WARNINGS ." w, ". BB_USERS ." u WHERE u.user_id = w.warning_user_id ORDER BY u.username";
	if (!$result = DB()->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain warning data", "", __LINE__, __FILE__, $sql);
	}
	$result = DB() -> sql_query($sql) or die(mysql_error());
	$warn_count = DB()->num_rows($result);
	$row = DB()->sql_fetchrowset($result);
	if ($choice_id == 3)
	{
		$lang_title_text = 'WARNING_STAT_TITLE';
		$lang_text = 'WARNING_STAT_DESC';	
	}
	$template->assign_vars(array(
		'TPL_WARNINGS_STAT' => true,
        "L_STAT_WARNING_LIST_TITLE" => $lang[$lang_title_text],
		"L_STAT_WARNING_TEXT" => $lang[$lang_text],		
		'S_LIST_SELECT' => $select_list,
		"S_WARNING_ACTION" => append_sid("admin_warning.php")
		));
//	$n = 0;
	$warn_user_count = 0;
	for($i = 0; $i < $warn_count; $i++)
	{
		$user_id = $row[$i]['warning_user_id'];
	//	Осуществляем выборку по количеству предупреждений юзера
		$sql = "SELECT w.*, u.username as poster FROM ". BB_WARNINGS ." w, ". BB_USERS ." u 
		WHERE warning_user_id = ". $user_id ." AND u.user_id = w.warning_poster_id";
		if (!$result = DB()->sql_query($sql))
		{
			message_die(GENERAL_ERROR, "Couldn't obtain warning count user data", "", __LINE__, __FILE__, $sql);
		}
		$result = DB() -> sql_query($sql) or die(mysql_error());
		$warn_user_count = DB()->num_rows($result);
		$user_row = DB()->sql_fetchrowset($result);
		//Разбираем по типу
		$user_warnings = 0;
		$user_banned = 0;
		$duration = 0;
		
		$duration_warn = 0;
		$duration_ban = 0;
		$infinity_warn = 0;
		$infinity_ban = 0;
		$poster = '';		
		for($k = 0; $k < $warn_user_count; $k++)
		{
			if ($poster != '')
			{
				if (substr_count($poster, $user_row[$k]['poster']) == 0)	
				{
					$poster .= ', '.'<a href="./../profile.php?mode=viewprofile&u='. $user_row[$k]['warning_poster_id'] .'" target="_blank">'. $user_row[$k]['poster'] .'</a>';
				}
			} else $poster .= '<a href="./../profile.php?mode=viewprofile&u='. $user_row[$k]['warning_poster_id'] .'" target="_blank">'. $user_row[$k]['poster'] .'</a>';
			$warning_type = $user_row[$k]['warning_type'];
			if ($warning_type == 1) 
			{
				$user_warnings = $user_warnings + 1;
				if ($user_row[$k]['warning_expires'] != -1)
				{
					$duration_warn = $duration_warn + round(($user_row[$k]['warning_expires'] - $user_row[$k]['warning_posted']) / 86400);
				} else $infinity_warn = $infinity_warn + 1;
			}
			if ($warning_type == 2) 
			{
				$user_banned = $user_banned + 1;
				if ($user_row[$k]['warning_expires'] != -1)
				{
					$duration_ban = $duration_ban + round(($user_row[$k]['warning_expires'] - $user_row[$k]['warning_posted']) / 86400);
				} else $infinity_ban = $infinity_ban + 1;
			}
			if ($user_row[$k]['warning_expires'] != -1)
			{
				$duration = $duration + round(($user_row[$k]['warning_expires'] - $user_row[$k]['warning_posted']) / 86400);
			}
		}
		$row_class = !($i % 2) ? 'row1' : 'row2';
		$total_warn = $total_warn + $user_warnings;
		$total_ban = $total_ban + $user_banned;		
	
		$template->assign_block_vars("WarnStat", array(
		"ROW_CLASS" => $row_class,		
		"USER_ID" => $row[$i]['warning_user_id'],
		"USER" => $row[$i]['username'],
		"COUNT_WARN" => $warn_user_count,
		"USER_WARNINGS" => $user_warnings,
		"USER_BANNED" => $user_banned,
		"DURATION_WARN" => $duration_warn,
		"DURATION_BAN" => $duration_ban,
		"INFINITY_WARN" => $infinity_warn,
		"INFINITY_BAN" => $infinity_ban,
		"DURATION" => $duration,
		"POSTER_NAME" => $poster		
		)) ;
//		$n++;		
	}
		$template->assign_block_vars("TotalStat", array(
		"TOTAL_USERS_WARN" => $warn_count,
		"TOTAL_WARN_COUNTER" => $total_warn,
		"TOTAL_BAN_COUNTER" => $total_ban,		
		)) ;

//	echo "<p>Строк в результирующей базе данных: ". $n ."</p>";
//	echo "<p>1 warn_user_id: ". $warn_user_id ."</p>";

//	Осуществляем выборку админов и модеров
	$sql = "SELECT DISTINCT w.warning_poster_id, u.user_id, u.username FROM ". BB_WARNINGS ." w, ". BB_USERS ." u WHERE u.user_id = w.warning_poster_id ORDER BY u.user_id";
	if (!$result = DB()->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain warning data", "", __LINE__, __FILE__, $sql);
	}
	$result = DB() -> sql_query($sql) or die(mysql_error());
	$warn_count = DB()->num_rows($result);
	$row = DB()->sql_fetchrowset($result);
	$warn_admin_count = 0;
	for($i = 0; $i < $warn_count; $i++)
	{
		$admin_id = $row[$i]['warning_poster_id'];
//------------------------------------
//		$sql = "SELECT w.*, u.username as poster FROM ". BB_WARNINGS ." w, ". BB_USERS ." u 
//		WHERE warning_user_id = ". $user_id ." AND u.user_id = w.warning_poster_id";

		//	Осуществляем выборку по количеству предупреждений юзера
		$sql = "SELECT w.*, u.username as towhom FROM ". BB_WARNINGS ." w, ". BB_USERS ." u
		WHERE warning_poster_id = ". $admin_id ." AND u.user_id = w.warning_user_id";
//		$sql = "SELECT * FROM ". BB_WARNINGS ." WHERE warning_poster_id = ". $admin_id;		
		if (!$result = DB()->sql_query($sql))
		{
			message_die(GENERAL_ERROR, "Couldn't obtain warning count admin data", "", __LINE__, __FILE__, $sql);
		}
		$result = DB() -> sql_query($sql) or die(mysql_error());
		$warn_admin_count = DB()->num_rows($result);
		$admin_row = DB()->sql_fetchrowset($result);
		$admin_warnings = 0;
		$admin_ban = 0;
		$duration = 0;		
		$duration_warn = 0;
		$duration_ban = 0;
		$infinity_warn = 0;
		$infinity_ban = 0;
		//$n = 0;
		$towhom = '';
		$totalusers_stat = 0;
		for($k = 0; $k < $warn_admin_count; $k++)
		{
			if ($towhom != '')
			{
				if (substr_count($towhom, $admin_row[$k]['towhom']) == 0)	
				{
					$towhom .= ', '.'<a href="./../profile.php?mode=viewprofile&u='. $admin_row[$k]['warning_user_id'] .'" target="_blank">'. $admin_row[$k]['towhom'] .'</a>';
					$totalusers_stat = $totalusers_stat + 1;					
				}
			} else 
			{
			$towhom .= '<a href="./../profile.php?mode=viewprofile&u='. $admin_row[$k]['warning_user_id'] .'" target="_blank">'. $admin_row[$k]['towhom'] .'</a>';			
			$totalusers_stat = $totalusers_stat + 1;
			}
			$warning_type = $admin_row[$k]['warning_type'];
			if ($warning_type == 1) 
			{
				$admin_warnings = $admin_warnings + 1;
				if ($admin_row[$k]['warning_expires'] != -1)
				{
					$duration_warn = $duration_warn + round(($admin_row[$k]['warning_expires'] - $admin_row[$k]['warning_posted']) / 86400);
				} else $infinity_warn = $infinity_warn + 1;
			}
			if ($warning_type == 2) 
			{
				$admin_ban = $admin_ban + 1;
				if ($admin_row[$k]['warning_expires'] != -1)
				{
					$duration_ban = $duration_ban + round(($admin_row[$k]['warning_expires'] - $admin_row[$k]['warning_posted']) / 86400);
				} else $infinity_ban = $infinity_ban + 1;
			}
			if ($admin_row[$k]['warning_expires'] != -1)
			{
				$duration = $duration + round(($admin_row[$k]['warning_expires'] - $admin_row[$k]['warning_posted']) / 86400);
			}
			//$n++;
		}		
	//echo "<p>Строк в результирующей базе данных: ". $n ."</p>";		
//------------------------------------
		$row_class = !($i % 2) ? 'row1' : 'row2';
		$total_warn = $total_warn + $admin_warnings;
		$total_ban = $total_ban + $admin_ban;
		
		$template->assign_block_vars("AdminStat", array(
		"ROW_CLASS" => $row_class,				
		"USER_ID" => $row[$i]['warning_poster_id'],
		"POSTER_NAME" => $row[$i]['username'],
		"COUNT_WARN" => $warn_admin_count,
		"USER_WARNINGS" => $admin_warnings,
		"USER_BANNED" => $admin_ban,
		"DURATION_WARN" => $duration_warn,
		"DURATION_BAN" => $duration_ban,
		"INFINITY_WARN" => $infinity_warn,
		"INFINITY_BAN" => $infinity_ban,
		"DURATION" => $duration,
		"TOTAL_USERS_STAT" => $totalusers_stat,		
		"TOWHOM" => $towhom
		)) ;



		
	}
}
print_page('admin_warning.tpl', 'admin');
?>